package com.smarthome.BoxAndroidNew;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.ArrayList;
import java.util.UUID;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;

import com.smarthome.BoxAndroidNew.R;
import com.smarthome.connect.TCPClient;

public class MyActivity extends Activity {
	private static final String TAG = "bluetooth2";
	private ListView mList;

	public ArrayList<String> arrayList;
	public MyCustomAdapter mAdapter;
	private TCPClient mTcpClient;
	String TAG1 = "Connectservice";
	String Tag2 = "SigninActivity";
	String Login2 = "Login";
	Socket socket = null;
	private static final UUID MY_UUID = UUID
			.fromString("00001101-0000-1000-8000-00805F9B34FB");
	public ConnectedThread mConnectedThread;
	// MAC-address of Bluetooth module (you must edit this line)
	private static String address = "20:14:03:27:02:87";
	public static MyActivity mainIns;
	Handler h;

	final int RECIEVE_MESSAGE = 1; // Status for Handler
	private BluetoothAdapter btAdapter = null;
	private BluetoothSocket btSocket = null;
	private StringBuilder sb = new StringBuilder();

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		// /

		mainIns = this;
		arrayList = new ArrayList<String>();

		final EditText editText = (EditText) findViewById(R.id.editText);
		Button send = (Button) findViewById(R.id.send_button);

		// relate the listView from java to the one created in xml
		mList = (ListView) findViewById(R.id.list);
		mAdapter = new MyCustomAdapter(this, arrayList);

		mList.setAdapter(mAdapter);
		h = new Handler() {
			public void handleMessage(android.os.Message msg) {
				switch (msg.what) {
				case RECIEVE_MESSAGE: // if receive massage
					byte[] readBuf = (byte[]) msg.obj;
					final String strIncom = new String(readBuf, 0, msg.arg1); // create
																				// string
																				// from
																				// bytes
																				// array
					sb.append(strIncom); // append string
					int endOfLineIndex = sb.indexOf("\n"); // determine the
					// end-of-line
					 if (endOfLineIndex > 0) { // if end-of-line,
					 final String sbprint = sb.substring(0, endOfLineIndex);
					// // extract string
					sb.delete(0, sb.length()); // and clear
					// txtUart.setText("Data from Arduino: " + sbprint); //
					// update TextView
					
					runOnUiThread(new Runnable() {

						public void run() {
							// TODO Auto-generated method stub
							arrayList.add("" + sbprint);
							
							mAdapter.notifyDataSetChanged();
						
						}

						
					});
					// btnOff.setEnabled(true);
					// btnOn.setEnabled(true);
					try {
						String tmp=new String();
						tmp=sbprint.trim();
						sendToServer(tmp);
						return;
					}
					catch(Exception ex) {};
					 }
					// Log.d(TAG, "...String:"+ sb.toString() + "Byte:" +
					// msg.arg1 + "...");
					 
					
				}
			};
		};

		initBT();
		
		try {
			// startService(new Intent(this, ConnectService.class));
			Log.d(LocalData.TAG_SERVICE, "inside try");
			startService(new Intent(MyActivity.this, ConnectService.class));
		} catch (Exception e) {
			Log.e(LocalData.TAG_SERVICE, "" + e);
		}
		JSONObject jslogin = new JSONObject();
		JSONObject jslogin2 = new JSONObject();

		Log.d(Tag2, "Doinbackground");
		try {
			if (LocalData.isConnectsuccess == true) {
				Log.d(Tag2, "Send-1");

				try {

					jslogin2.put(LocalData.TAG_USERNAME, "Son");
					jslogin2.put(LocalData.TAG_PASS, "123");
					jslogin.put("tag", "login");
					jslogin.put("strjson", jslogin2);
					Log.d(Tag2, "Put Json-2");
					Log.i(Tag2, "JsonString: " + jslogin.toString());
				} catch (JSONException e) {
					Log.e(Tag2, "JSON failed-3" + e);
				}
				ConnectService.mTcpClient.sendMessage(jslogin.toString());

				Log.d(Tag2, "JsonString: " + jslogin.toString());
			} else {
				Log.e(Tag2, "Connect not success-4"
						+ LocalData.isConnectsuccess);
			}
		} catch (Exception e) {
			Log.e(Tag2, "Fail parse Json-5" + e);
		}

		send.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {

				String message = editText.getText().toString();
				if (mConnectedThread == null)
					initBT();
				// add the text in the arrayList
				arrayList.add("" + message);
				try {
					if (LocalData.isConnectsuccess == true) {
						if (ConnectService.mTcpClient != null) {
							JSONObject jsstatus = new JSONObject();
							JSONObject jsdevicestatus = new JSONObject();
							// jsdevicestatus.put(""+position, true);

							jsstatus.put(LocalData.TAG_USERGROUP, ".gt");
							jsstatus.put(LocalData.TAG, LocalData.TAG_STATUS);
							jsstatus.put(LocalData.TAG_STRJSON, message);
							jsstatus.put("Box", true);
							ConnectService.mTcpClient.sendMessage(jsstatus
									.toString());
							Log.d("switch",
									"Inside try 1" + jsstatus.toString());
						} else
							Log.e("Griddevice",
									"Không connect được sao mà gửi-1"
											+ LocalData.isConnectsuccess);
					} else
						Log.e("Griddevice", "Không connect được sao mà gửi-2");
				} catch (Exception e) {

					Log.e("Griddevice", "" + e);

				}
				// mConnectedThread.write("1");
				// refresh the list
				mAdapter.notifyDataSetChanged();
				editText.setText("");
			}
		});
		// mainIns = new MyActivity();
	}
public void sendDataRespone(String message)
{
	try {
		if (LocalData.isConnectsuccess == true) {
			if (ConnectService.mTcpClient != null) {
				JSONObject jsstatus = new JSONObject();
				JSONObject jsdevicestatus = new JSONObject();
				// jsdevicestatus.put(""+position, true);
               
				jsstatus.put(LocalData.TAG_USERGROUP, ".gt");
				jsstatus.put(LocalData.TAG, LocalData.TAG_STATUS);
				jsstatus.put(LocalData.TAG_STRJSON, message);

				ConnectService.mTcpClient.sendMessage(jsstatus
						.toString());
				Log.d("switch",
						"Inside try 1" + jsstatus.toString());
			} else
				Log.e("Griddevice",
						"Không connect được sao mà gửi-1"
								+ LocalData.isConnectsuccess);
		} else
			Log.e("Griddevice", "Không connect được sao mà gửi-2");
	} catch (Exception e) {

		Log.e("Griddevice", "" + e);

	}	
};
	private BluetoothSocket createBluetoothSocket(BluetoothDevice device)
			throws IOException {
		if (Build.VERSION.SDK_INT >= 10) {
			try {
				final Method m = device.getClass().getMethod(
						"createInsecureRfcommSocketToServiceRecord",
						new Class[] { UUID.class });
				return (BluetoothSocket) m.invoke(device, MY_UUID);
			} catch (Exception e) {
				// Log.e(TAG, "Could not create Insecure RFComm Connection",e);
			}
		}
		return device.createRfcommSocketToServiceRecord(MY_UUID);
	}

	public void initBT() {
		btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth
		// adapter
		checkBTState();

		Log.d(TAG, "...onResume - try connect...");

		// Set up a pointer to the remote node using it's address.
		BluetoothDevice device = btAdapter.getRemoteDevice(address);

		// Two things are needed to make a connection:
		// A MAC address, which we got above.
		// A Service ID or UUID. In this case we are using the
		// UUID for SPP.

		try {
			btSocket = createBluetoothSocket(device);
		} catch (IOException e) {
			errorExit("Fatal Error", "In onResume() and socket create failed: "
					+ e.getMessage() + ".");
		}

		/*
		 * try { btSocket = device.createRfcommSocketToServiceRecord(MY_UUID); }
		 * catch (IOException e) { errorExit("Fatal Error",
		 * "In onResume() and socket create failed: " + e.getMessage() + "."); }
		 */

		// Discovery is resource intensive. Make sure it isn't going on
		// when you attempt to connect and pass your message.
		btAdapter.cancelDiscovery();

		// Establish the connection. This will block until it connects.
		Log.d(TAG, "...Connecting...");
		try {
			btSocket.connect();
			Log.d(TAG, "....Connection ok...");
		} catch (IOException e) {
			try {
				btSocket.close();
			} catch (IOException e2) {
				errorExit("Fatal Error",
						"In onResume() and unable to close socket during connection failure"
								+ e2.getMessage() + ".");
			}
		}

		// Create a data stream so we can talk to server.
		Log.d(TAG, "...Create Socket...");

		mConnectedThread = new ConnectedThread(btSocket);
		mConnectedThread.start();
	};
	public void sendToServer(String tmp) {
		// TODO Auto-generated method stub
		try {
			if (LocalData.isConnectsuccess == true) {
				if (ConnectService.mTcpClient != null) {
					JSONObject jsstatus = new JSONObject();
					JSONObject jsdevicestatus = new JSONObject();
					// jsdevicestatus.put(""+position, true);
                   try {
					char deviceStatus[];
                    deviceStatus=tmp.toCharArray();
                    if (deviceStatus[0]=='0') 
					jsdevicestatus.put("1",true);
                    else jsdevicestatus.put("1",false);
                    if (deviceStatus[1]=='0') 
    					jsdevicestatus.put("2",true);
                        else jsdevicestatus.put("2",false); 
                    if (deviceStatus[2]=='0') 
        					jsdevicestatus.put("3",true);
                        else jsdevicestatus.put("3",false);
                   }
                   catch(Exception ex ) {};
					jsstatus.put(LocalData.TAG_USERGROUP, ".gt");
					jsstatus.put(LocalData.TAG, LocalData.TAG_STATUS);
					jsstatus.put(LocalData.TAG_STRJSON, jsdevicestatus);

					ConnectService.mTcpClient.sendMessage(jsstatus
							.toString());
					Log.d("switch",
							"Inside try 1" + jsstatus.toString());
				} else
					Log.e("Griddevice",
							"Không connect được sao mà gửi-1"
									+ LocalData.isConnectsuccess);
			} else
				Log.e("Griddevice", "Không connect được sao mà gửi-2");
		} catch (Exception e) {

			Log.e("Griddevice", "" + e);

		}
	}
	@Override
	public void onResume() {
		super.onResume();
		if (mConnectedThread == null)
			initBT();

	}

	@Override
	public void onPause() {
		super.onPause();

		Log.d(TAG, "...In onPause()...");

		try {
			btSocket.close();
		} catch (IOException e2) {
			errorExit("Fatal Error", "In onPause() and failed to close socket."
					+ e2.getMessage() + ".");
		}
	}

	private void errorExit(String title, String message) {
		Toast.makeText(getBaseContext(), title + " - " + message,
				Toast.LENGTH_LONG).show();
		finish();
	}

	private void checkBTState() {
		// Check for Bluetooth support and then check to make sure it is turned
		// on
		// Emulator doesn't support Bluetooth and will return null
		if (btAdapter == null) {
			errorExit("Fatal Error", "Bluetooth not support");
		} else {
			if (btAdapter.isEnabled()) {
				Log.d(TAG, "...Bluetooth ON...");
			} else {
				// Prompt user to turn on Bluetooth
				Intent enableBtIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_ENABLE);
				startActivityForResult(enableBtIntent, 1);
			}
		}
	}

	public class ConnectedThread extends Thread {

		public ConnectedThread(BluetoothSocket socket) {
			InputStream tmpIn = null;
			OutputStream tmpOut = null;

			// Get the input and output streams, using temp objects because
			// member streams are final
			try {
				tmpIn = socket.getInputStream();
				tmpOut = socket.getOutputStream();
			} catch (IOException e) {
			}

			mmInStream = tmpIn;
			mmOutStream = tmpOut;
		}

		public void run() {
			byte[] buffer = new byte[256]; // buffer store for the stream
			int bytes; // bytes returned from read()

			// Keep listening to the InputStream until an exception occurs
			while (true) {
				try {
					// Read from the InputStream
					bytes = mmInStream.read(buffer); // Get number of bytes and
														// message in "buffer"
					h.obtainMessage(RECIEVE_MESSAGE, bytes, -1, buffer)
							.sendToTarget(); // Send to message queue Handler
				} catch (IOException e) {
					break;
				}
			}
		}

	}

	private InputStream mmInStream;
	private OutputStream mmOutStream;

	/* Call this from the main activity to send data to the remote device */
	public void write(String message) {
		Log.d(TAG, "...Data to send: " + message + "...");
		byte[] msgBuffer = message.getBytes();
		try {
			mmOutStream.write(msgBuffer);
		} catch (IOException e) {
			Log.d(TAG, "...Error data send: " + e.getMessage() + "...");
		}
	}

	private Authen model = null;

	public class Loader extends AsyncTask<Void, Void, Authen> {
		messageRequest strStatus = new messageRequest();

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

		}

		@Override
		protected Authen doInBackground(Void... arg0) {

			model = JSonparse.getauthen(LocalData.strreceiver);
			strStatus = JSonparse.getMess(model.getStrjson());

			return model;
		}

		@Override
		protected void onPostExecute(final Authen model) {
			Log.i("TESTTROLW", "TESTTROLW: 9");
			super.onPostExecute(model);// sfsmdf

			try {
				Log.d(Tag2, "in postexecute -1 " + LocalData.islogin);
				Log.d(Tag2,
						"Info " + model.getSuccess() + "---" + model.getTag()
								+ " | " + model.getUser_group());
				if (LocalData.isConnectsuccess == true) {
					// if (!model.getSuccess())
					// {
					// alertmess("Đăng nhập thất bại" +model.getSuccess() );
					// }
					// else {
					LocalData.usergroup = model.getUser_group();
					// Log.d("Data reciver",
					// strStatus.getDeviceId()+"   "+strStatus.getValue());
					// }
				} else {

				}
			} catch (Exception e) {
				e.printStackTrace();

				Log.d(Tag2, "in postexecute -2 " + e);
			}
		}

	}

	public void OnRecievedData(final messageRequest data) {
		// TODO Auto-generated method stub

		// mConnectedThread.run();
		if (data.getDv1() != null) {

			if (data.getDv1()) {
				write("1");
				Log.d("dv1", "ON");
				arrayList.add("dv1 on");
				
				;

			} else {

				if (!data.getDv1()) {

					write("2");
					arrayList.add("dv1 off");
					Log.d("dv1", "OFF");
				}
			}
		}
		if (data.getDv2() != null) {

			if (data.getDv2()) {
				write("3"); // 2: On
				arrayList.add("dv2 on");
			} else {

				if (!data.getDv2()) {
					write("4"); // 2:off
					arrayList.add("dv2 off");
				}
			}
		}
		if (data.getDv3() != null) {

			if (data.getDv3()) {
				write("5"); // 3: On
				arrayList.add("dv3 on");
			} else {

				if (!data.getDv3()) {
					write("6"); // 3:off
					arrayList.add("dv3 off");
				}
			}
		}
		if (data.getDv4() != null) {

			if (data.getDv4()) {
				write("7"); // 4: On

			} else {

				if (!data.getDv4()) {
					write("8"); // 4:off

				}
			}
		}
		
		 mAdapter.notifyDataSetChanged();
	}
}
